package org.example.mine.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.example.mine.service.TopUpService;
import org.example.model.domain.express.ExpressDetial;
import org.example.model.domain.mine.ExpressRechargeRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;


@ConfigurationProperties(prefix = "alipay")
@Component
@Data
@Slf4j
public class AlipayTemplate {
    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    @Value("{alipay.appId}")

    public String appId;

    // 应用私钥，就是工具生成的应用私钥
    @Value("{alipay.merchantPrivateKey}")
    public String merchantPrivateKey;
    // 支付宝公钥,对应APPID下的支付宝公钥。
    @Value("{alipay.alipayPublicKey}")
    public String alipayPublicKey;

    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    @Value("{alipay.notifyUrl}")
    public String notifyUrl;
    //同步通知，支付成功，一般跳转到成功页
    @Value("{alipay.returnUrl}")
    public String returnUrl;

    // 签名方式
    @Value("{alipay.signType}")
    private String signType;

    // 字符编码格式
    @Value("{alipay.charset}")
    private String charset;

    //订单超时时间
    private String timeout = "1m";
    // 支付宝网关；https://openapi-sandbox.dl.alipaydev.com/gateway.do
    @Value("{alipay.gatewayUrl}")
    public String gatewayUrl;


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TopUpService topUpService;

    public String pay(ExpressRechargeRecord expressRechargeRecord) throws AlipayApiException {
        log.info("订单信息：{}", expressRechargeRecord);

        String privateKey = "MIIEvQIBADANBgkqhkiG9w0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/I6ZuqK+dXNgYcN2pmPEWkxSjA/ocWxsb5AxhYOWD8HGVo9WVI8uKaTmflf/YQxonJ/EB8wZFp5eBl0EezRCm7AOM2hVE8/uf+sn/guttPERkuzQhYQi8u1iTckwFz1TI5EUb0xn4G1eX4v3VbVcAxoxCbBR+kRiyFWHqLtThAoGAMLgESzZK9bI07KI6LWMYWsgTaRX9LJ3FQtzdtbSXw+cCjwBhrNMYFT/a0asAPo7Kl/QMcFE1eyhwQJNGLcb9A35reoF0eS6KBSTMq6XKL/oF9eP1tu1ycjNMAVaFEEg6tKDamGcmQOHq9rFzOJ5aKtZs+BLJZyEnws9jRj1ITekCgYEAhqFyXrXuswk9YoOxg2q8X9J7HmuYt44zePUZhnx6xwVm+sbge3zVQt/Ig54yRHulqZEHA5Xdx09m5IkIHA/ZZXkD+yROC78zfemhtfA2h0Hr1omI3BnFbTvPiAEwaNaG9caorTuP00/GyYtpdKEYtrvUXGqqKe82xW78vBvQdFQ=";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnyjJAPOoIrKWIvFVC5AkxUF1c4RH/9tVwicHJUiM3BbyZPqf+wjtP+16Mp6Lwv7sGy0r2HdmP3C8TS1zvtmYzLTlfiRQIpRiBQq7nO8X7WLxHofIIuqgX5oB+SkED3VEF+oJ9uMlkQayxuAxDDhR9bP2AvB3ZcDYJHkc7J84gLJ6Z6rvQWC0j1Sh+xX1ulYrsWkVisuju3CYCWKKqMnrJNfLeqLSr7GvMgPz+ImCrPC7LbytGpVs7wcuRLyS1ZjkruBjYTjhEju49z27kDkq2k71v2hcYwIRDde+s7cuYx2gkqJdn2lZaPp+LhbF7qFn6lHiuTtWISypSzeLSFqLLQIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000140606941");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        model.setOutTradeNo(expressRechargeRecord.getTransactionNumber());
        model.setTotalAmount(String.valueOf(expressRechargeRecord.getActualPayment()));
        model.setSubject("余额支付");
        model.setProductCode("QUICK_WAP_WAY");
        model.setSellerId("2088721041666476");
        request.setBizModel(model);
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            ExpressDetial expressDetial = new ExpressDetial();
            expressDetial.setRegisterIp(Long.parseLong(expressRechargeRecord.getRegisterIp()));
            expressDetial.setAccountBalance(BigDecimal.valueOf(new BigDecimal(expressRechargeRecord.getBalanceAfterRecharging()).doubleValue()));
            System.err.println(expressDetial);
            redisTemplate.boundValueOps(expressRechargeRecord.getTransactionNumber()).set(expressDetial, 60*15, TimeUnit.SECONDS);
            return pageRedirectionData;
        } else {
            System.out.println("调用失败");
            topUpService.topupfail(expressRechargeRecord.getId());
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;
    }
//
//    public String pay(ExpressRechargeRecord record) throws
//            AlipayApiException {
//
//        //1、根据支付宝的配置生成一个支付客户端
//         AlipayClient alipayClient = new
//                DefaultAlipayClient(gatewayUrl, appId, merchantPrivateKey,
//                "json", charset, alipayPublicKey, signType);
//
//        //2、创建一个支付请求，并设置请求参数
//        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//        alipayRequest.setReturnUrl(returnUrl);
//        ExpressDetial expressDetial = new ExpressDetial();
//        expressDetial.setRegisterIp(Long.parseLong(record.getRegisterIp()));
//        expressDetial.setAccountBalance(BigDecimal.valueOf(new BigDecimal(record.getBalanceAfterRecharging()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
//        redisTemplate.boundValueOps(record.getTransactionNumber()).set(expressDetial, 60*15, TimeUnit.SECONDS);
//        try {
//            alipayRequest.setNotifyUrl(notifyUrl);
//        } catch (Exception e) {
////            失败后调用
//            topUpService.topupfail(record.getId());
//            throw new RuntimeException(e);
//        }
//
//        Integer id = record.getId();
//        String interfaceInfoId = record.getTransactionNumber();
//        Double money = record.getActualPayment();
//
//
//        alipayRequest.setBizContent(" {\"out_trade_no\":\"" + interfaceInfoId + "\","
//                + "\"total_amount\":\"" + money + "\","
//                + "\"subject\":\"" + interfaceInfoId + "\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//        String result = alipayClient.pageExecute(alipayRequest).getBody();
//        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
//        System.out.println("支付宝的响应：" + result);
//        return result;
//    }
}
